import type {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  InternalAxiosRequestConfig
} from 'axios'
import axios from 'axios'
// import { useCounterStore } from "@/stores/counter"
// 定义任意类型接口
interface anyType {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  [key: string]: any | (string | number)
}
// let msgBox: MessageHandler | null = null
class Request {
  // axios 实例
  instance: AxiosInstance

  constructor(config?: AxiosRequestConfig) {
    this.instance = axios.create(config)
    this.instance.interceptors.request.use(
      (res: InternalAxiosRequestConfig) => {
        // const store = useCounterStore()
        if (config && config.url) {
          res.baseURL = config.url
        } else {
          res.baseURL = import.meta.env.VITE_API_URL_API
        }
        return res
      },
      (err: Error) => err
    )
    this.instance.interceptors.response.use(
      // 因为我们接口的数据都在res.data下，所以我们直接返回res.data
      (res: AxiosResponse) => {
        if (res.status == 200) {
          if (res.data.data) {
            return res.data.data
          } else {
            return res.data
          }
        } else {
          if (res) {
            checkStatus(res.status)
          }
        }
        return res.data
      },
      (err: Error) => err
    )
  }

  // 常用请求方法封装
  get<T>(url: string, params?: anyType, _object = {}): Promise<T> {
    return this.instance.get(url, { params, ..._object })
  }
  post<T>(url: string, data?: anyType, _object = {}): Promise<T> {
    return this.instance.post(url, data, _object)
  }
  put<T>(url: string, params?: anyType, _object = {}): Promise<T> {
    return this.instance.put(url, params, _object)
  }
  delete<T>(url: string, params?: anyType, _object = {}): Promise<T> {
    return this.instance.delete(url, { params, ..._object })
  }
}

const checkStatus = (status: number): void => {
  switch (status) {
    case 404:
      console.warn('资源不存在！')
      break
    case 405:
      console.warn('请求方式错误！')
      break
    case 500:
      console.warn('服务器异常！')
      break
    default:
      console.warn('请求失败！')
  }
}

export default Request
